package com.hera.base.web.vaadin.mantenimiento;

import static com.hera.base.util.InputData.getIntegerData;
import static com.hera.base.util.InputData.getObjectData;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hera.base.util.Constantes;
import com.hera.base.util.FiltroDTO;
import com.hera.base.util.TableCustom;
import com.hera.base.web.BaseUI;
import com.hera.base.web.MantenimientoMaestroDetalle;
import com.hera.process.config.domain.Department;
import com.hera.process.config.domain.ParameterDetail;
import com.hera.process.config.rest.delegate.ConfigDelegate;
import com.hera.process.config.rest.delegate.SecurityDelegate;
import com.hera.process.config.rest.delegate.WorkflowDelegate;
import com.hera.process.security.domain.User;
import com.hera.process.workflow.domain.Process;
import com.hera.process.workflow.domain.ProcessGroup;
import com.hera.process.workflow.domain.Stage;
import com.hera.process.workflow.domain.StageUser;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class StageUserUI extends BaseUI implements MantenimientoMaestroDetalle,ClickListener {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	/**
	 * 
	 */
	private static final long serialVersionUID = -6181728914647084015L;
	@AutoGenerated
	private VerticalLayout mainLayout;
	@AutoGenerated
	private VerticalLayout verticalLayout_1;
	@AutoGenerated
	private HorizontalLayout lytMaestro;
	@AutoGenerated
	private VerticalLayout pnlFormulario;
	@AutoGenerated
	private HorizontalLayout horizontalLayout_5;
	@AutoGenerated
	private Button btnEliminar;
	@AutoGenerated
	private Button btnNuevo;
	@AutoGenerated
	private TextField txtPrioridad;
	@AutoGenerated
	private ComboBox cmbValue;
	@AutoGenerated
	private ComboBox cmbType;
	@AutoGenerated
	private Label lbltitulo;
	@AutoGenerated
	private HorizontalLayout lytTablaMaestra;
	@AutoGenerated
	private TableCustom tblfMaestro;
	private Stage stage;
	private Process process;
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public StageUserUI() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
	}
	
	public StageUserUI(Stage stage, Process process) {
		buildMainLayout();
		setCompositionRoot(mainLayout);
		this.stage = stage;
		this.process = process;
	}
	
	public void setStage(Stage stage){
		this.stage = stage;
	}

	private static final Logger log = Logger.getLogger(StageUserUI.class);
	
	@Autowired
	ConfigDelegate configDelegate;
	@Autowired
	WorkflowDelegate workflowDelegate;
	@Autowired
	SecurityDelegate securityDelegate;
	boolean esNuevo;
	boolean esNuevoDetalle;
	StageUser stageUser;
	
	
	@Override
	public void buttonClick(ClickEvent event) {
		if(event.getButton().equals(btnEliminar)){
			eliminarMaestro();
		}else if(event.getButton().equals(btnNuevo)){
			guardarMaestro();
		}
		
	}

	@Override
	public void cargarFormulario() {
	
		txtPrioridad.setNullRepresentation("");
		
		log.info("INCIO +++++++++");
		esNuevo = true;
		stageUser = null;

		btnEliminar.setVisible(false);
		btnEliminar.addClickListener(this);
		
		
		btnNuevo.setVisible(false);
		btnNuevo.addClickListener(this);
		btnNuevo.setCaption("Nuevo");
				
		BeanItemContainer<ParameterDetail> type = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail = new ParameterDetail();
		listsDetail.setIdParameterDetail(Constantes.TipoStageUser.ID);
		type.addAll(configDelegate.findDetailList(listsDetail));
		cmbType.setContainerDataSource(type);
		cmbType.setItemCaptionPropertyId("name");
		cmbType.setInputPrompt("Tipo");
		cmbType.setImmediate(true);
		
		cmbValue.setInputPrompt("Valor");
		
		//tblfMaestro.setTitulo(" Lista Formularios del Stage " + stage.getName());
		tblfMaestro.setHeight("150px");
		
		tblfMaestro.addColumn("type.name", "Tipo", 100, true, String.class);
		tblfMaestro.addColumn("priority", "Prioridad", 50, true, String.class);
		//tblfMaestro.addColumn("schema", "Modo", 250, true, String.class);
		
		tblfMaestro.construir();
		tblfMaestro.addTextChangeListener(new TextChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void textChange(TextChangeEvent event) {
				buscarMaestro(event);
				
			}
		});
		
		tblfMaestro.addValueChangeListener(new ValueChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				stageUser = (StageUser)tblfMaestro.getSelectedItem(event);
				esNuevo = (stageUser==null);
				tblfMaestro.limpiarFiltro();
				if(esNuevo){
					limpiarMaestro();
					btnEliminar.setVisible(false);
				}else{
					btnEliminar.setVisible(true);
					btnNuevo.setVisible(true);
					btnNuevo.setCaption("Modificar");
					cmbType.setValue(stageUser.getType());
					//cmbValue.setValue(stageUser.geti());
					if(Constantes.TipoStageUser.USUARIO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						cmbValue.setValue(stageUser.getUser());
					}else if(Constantes.TipoStageUser.DEPARTAMENTO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						cmbValue.setValue(stageUser.getDepartment());
					}else if(Constantes.TipoStageUser.GRUPO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						cmbValue.setValue(stageUser.getProcessGroup());
					}
					txtPrioridad.setValue(""+stageUser.getPriority());
				}				
				log.info("Fin Cargar Formulario DynamicForm stage ");
				
			}
		});
		
		cmbType.addValueChangeListener(new Property.ValueChangeListener() {		    
			private static final long serialVersionUID = 519197261448804864L;
			public void valueChange(ValueChangeEvent event) {
				cmbValue.removeAllItems();
				cmbValue.setValue(null);
				if(cmbType.getValue() != null){
					if(Constantes.TipoStageUser.USUARIO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						BeanItemContainer<User> usuarios = new BeanItemContainer<User>(User.class);						
						usuarios.addAll(securityDelegate.findAllSysUsers(new FiltroDTO()));
						cmbValue.setContainerDataSource(usuarios);
						cmbValue.setItemCaptionPropertyId("fullName");
					}else if(Constantes.TipoStageUser.DEPARTAMENTO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						BeanItemContainer<Department> departamentos = new BeanItemContainer<Department>(Department.class);						
						departamentos.addAll(configDelegate.findAllDepartments(new FiltroDTO()));
						cmbValue.setContainerDataSource(departamentos);
						cmbValue.setItemCaptionPropertyId("name");
					}else if(Constantes.TipoStageUser.GRUPO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
						BeanItemContainer<ProcessGroup> grupos = new BeanItemContainer<ProcessGroup>(ProcessGroup.class);						
						grupos.addAll(workflowDelegate.findAllProcessGroups(new FiltroDTO()));
						cmbValue.setContainerDataSource(grupos);
						cmbValue.setItemCaptionPropertyId("name");
					}
				}		        
		    }
		});
		
	}

	@Override
	public void buscarMaestro() {
		buscarMaestro(null);
		
	}

	@Override
	public void buscarMaestro(TextChangeEvent event) {
		log.info("inicio Buscar stageuser");
		//FiltroDTO filtroDTO = tblfMaestro.getFiltroDTO(event);
		List<StageUser> lstStageUser = workflowDelegate.findStageUserByStage(stage);
		tblfMaestro.setLstData(lstStageUser);
		limpiarMaestro();
		log.info("fin stageuser");
	}

	@Override
	public void limpiarMaestro() {
		log.info("inicio limpiarMaestro");
		btnNuevo.setVisible(true);
		btnNuevo.setCaption("Nuevo");
		cmbType.setValue(null);
		cmbValue.setValue(null);
		txtPrioridad.setValue("");
	
			
		log.info("fin limpiarMaestro");
		
	}

	@Override
	public void eliminarMaestro() {
		
		log.info("inicio eliminarMaestro");
		workflowDelegate.deleteStageUser(stageUser);
		buscarMaestro();
		limpiarMaestro();
		log.info("fin eliminarMaestro");	
		
	}

	@Override
	public void guardarMaestro() {
		
		log.info("inicio guardarMaestro");
		if(esNuevo){
			stageUser=new StageUser();
			obtenerDatosFormulario(stageUser);
			stageUser.setStage(stage);
			
			workflowDelegate.createStageUser(stageUser);
		}else{
			obtenerDatosFormulario(stageUser);
			workflowDelegate.updatedStageUser(stageUser);
		}
		limpiarMaestro();
		buscarMaestro();
		log.info("fin guardarMaestro");
	}

	@Override
	public void buscarDetalle() {
		
		
	}

	@Override
	public void buscarDetalle(TextChangeEvent event) {
		
		
	}

	@Override
	public void limpiarDetalle() {
		
		
	}

	@Override
	public void eliminarDetalle() {
		
		
	}

	@Override
	public void guardarDetalle() {
		
		
	}

	@Override
	protected void postConstruct() {
		cargarFormulario();
		buscarMaestro();
		
	}

private void obtenerDatosFormulario(StageUser stageUser) {		
	stageUser.setType(getObjectData(cmbType, ParameterDetail.class, "Tipo"));
	//stageUser.se(getObjectData(cmbt, ListsDetail.class, "Modo Presentación"));
	stageUser.setPriority(getIntegerData(txtPrioridad, "Prioridad"));
		
	if(Constantes.TipoStageUser.USUARIO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
		stageUser.setUser(getObjectData(cmbValue, User.class, "Valor"));
	}else if(Constantes.TipoStageUser.DEPARTAMENTO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
		stageUser.setDepartment(getObjectData(cmbValue, Department.class,"Valor"));
	}else if(Constantes.TipoStageUser.GRUPO.equals(((ParameterDetail)cmbType.getValue()).getIdParameterDetail())){
		stageUser.setProcessGroup(getObjectData(cmbValue, ProcessGroup.class, "Valor"));
	}
	
}

@AutoGenerated
private VerticalLayout buildMainLayout() {
	// common part: create layout
	mainLayout = new VerticalLayout();
	mainLayout.setImmediate(false);
	mainLayout.setWidth("-1px");
	mainLayout.setHeight("-1px");
	mainLayout.setMargin(false);
	
	// top-level component properties
	setWidth("-1px");
	setHeight("-1px");
	
	// verticalLayout_1
	verticalLayout_1 = buildVerticalLayout_1();
	mainLayout.addComponent(verticalLayout_1);
	
	return mainLayout;
}

@AutoGenerated
private VerticalLayout buildVerticalLayout_1() {
	// common part: create layout
	verticalLayout_1 = new VerticalLayout();
	verticalLayout_1.setImmediate(false);
	verticalLayout_1.setWidth("-1px");
	verticalLayout_1.setHeight("-1px");
	verticalLayout_1.setMargin(false);
	verticalLayout_1.setSpacing(true);
	
	// lytMaestro
	lytMaestro = buildLytMaestro();
	verticalLayout_1.addComponent(lytMaestro);
	
	return verticalLayout_1;
}

@AutoGenerated
private HorizontalLayout buildLytMaestro() {
	// common part: create layout
	lytMaestro = new HorizontalLayout();
	lytMaestro.setImmediate(false);
	lytMaestro.setWidth("-1px");
	lytMaestro.setHeight("-1px");
	lytMaestro.setMargin(false);
	lytMaestro.setSpacing(true);
	
	// lytTablaMaestra
	lytTablaMaestra = buildLytTablaMaestra();
	lytMaestro.addComponent(lytTablaMaestra);
	
	// pnlFormulario
	pnlFormulario = buildPnlFormulario();
	lytMaestro.addComponent(pnlFormulario);
	
	return lytMaestro;
}

@AutoGenerated
private HorizontalLayout buildLytTablaMaestra() {
	// common part: create layout
	lytTablaMaestra = new HorizontalLayout();
	lytTablaMaestra.setImmediate(false);
	lytTablaMaestra.setWidth("270px");
	lytTablaMaestra.setHeight("-1px");
	lytTablaMaestra.setMargin(false);
	
	// tblfMaestro
	tblfMaestro = new TableCustom();
	tblfMaestro.setImmediate(false);
	tblfMaestro.setWidth("-1px");
	tblfMaestro.setHeight("-1px");
	lytTablaMaestra.addComponent(tblfMaestro);
	
	return lytTablaMaestra;
}

@AutoGenerated
private VerticalLayout buildPnlFormulario() {
	// common part: create layout
	pnlFormulario = new VerticalLayout();
	pnlFormulario.setImmediate(false);
	pnlFormulario.setWidth("-1px");
	pnlFormulario.setHeight("-1px");
	pnlFormulario.setMargin(false);
	pnlFormulario.setSpacing(true);
	
	// lbltitulo
	lbltitulo = new Label();
	lbltitulo.setStyleName("titulo");
	lbltitulo.setImmediate(false);
	lbltitulo.setWidth("-1px");
	lbltitulo.setHeight("-1px");
	lbltitulo.setValue("Usuarios");
	pnlFormulario.addComponent(lbltitulo);
	pnlFormulario.setComponentAlignment(lbltitulo, new Alignment(20));
	
	// cmbType
	cmbType = new ComboBox();
	cmbType.setStyleName("fieldRequired");
	cmbType.setImmediate(false);
	cmbType.setDescription("Tipo");
	cmbType.setWidth("-1px");
	cmbType.setHeight("-1px");
	pnlFormulario.addComponent(cmbType);
	
	// cmbValue
	cmbValue = new ComboBox();
	cmbValue.setStyleName("fieldRequired");
	cmbValue.setImmediate(false);
	cmbValue.setDescription("Value");
	cmbValue.setWidth("-1px");
	cmbValue.setHeight("-1px");
	pnlFormulario.addComponent(cmbValue);
	
	// txtPrioridad
	txtPrioridad = new TextField();
	txtPrioridad.setStyleName("fieldRequired");
	txtPrioridad.setImmediate(false);
	txtPrioridad.setDescription("Prioridad");
	txtPrioridad.setWidth("-1px");
	txtPrioridad.setHeight("-1px");
	txtPrioridad.setInputPrompt("Prioridad");
	pnlFormulario.addComponent(txtPrioridad);
	
	// horizontalLayout_5
	horizontalLayout_5 = buildHorizontalLayout_5();
	pnlFormulario.addComponent(horizontalLayout_5);
	
	return pnlFormulario;
}

@AutoGenerated
private HorizontalLayout buildHorizontalLayout_5() {
	// common part: create layout
	horizontalLayout_5 = new HorizontalLayout();
	horizontalLayout_5.setImmediate(false);
	horizontalLayout_5.setWidth("-1px");
	horizontalLayout_5.setHeight("-1px");
	horizontalLayout_5.setMargin(false);
	horizontalLayout_5.setSpacing(true);
	
	// btnNuevo
	btnNuevo = new Button();
	btnNuevo.setCaption("Nuevo");
	btnNuevo.setImmediate(true);
	btnNuevo.setWidth("-1px");
	btnNuevo.setHeight("-1px");
	horizontalLayout_5.addComponent(btnNuevo);
	
	// btnEliminar
	btnEliminar = new Button();
	btnEliminar.setCaption("Eliminar");
	btnEliminar.setImmediate(true);
	btnEliminar.setWidth("-1px");
	btnEliminar.setHeight("-1px");
	horizontalLayout_5.addComponent(btnEliminar);
	
	return horizontalLayout_5;
}
	
	
}
